package com.core.exception;

import com.core.result.CmdResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

/**
 * 自定义异常返回前端
 * @author hc
 * @CreateTime 2025/7/29 17:17
 */
@Component
public class GlobalExceptionHandler implements RouterInterceptor {

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        try {
            chain.doIntercept(ctx, mainHandler);
        } catch (BizException e) {
            CmdResult<?> result = CmdResult.error(e.getCode(), e.getMessage());
            ctx.status(Integer.parseInt(result.getCode()));
            ctx.render(result);
        } catch (Throwable e) {
            CmdResult<?> result = CmdResult.error("500", "服务端运行出错");
            ctx.status(500);
            ctx.render(result);
        }
    }
}
